package com.jie.demo.mockmvc;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * 集成Web环境方式
 * 通过配置文件，启动容器
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SpringMockMvcCases {
    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;
    private MockMvc mockMvc2;
    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    //全局配置
    public void setUpGlobal(){
        mockMvc2 = MockMvcBuilders.webAppContextSetup(wac)
                //.defaultRequest(get("/user/1").requestAttr("default", true)) //默认请求 如果其是Mergeable类型的，会自动合并的哦mockMvc.perform中的RequestBuilder
                .alwaysDo(print())  //默认每次执行请求后都做的动作
                .alwaysExpect(request().attribute("default", true)) //默认每次执行后进行验证的断言
                .build();
    }

    /**
     * 从名字可以看出，RequestBuilder用来构建请求的，其提供了一个方法
     * buildRequest(ServletContext servletContext)用于构建MockHttpServletRequest；
     * 其主要有两个子类MockHttpServletRequestBuilder和MockMultipartHttpServletRequestBuilder（如文件上传使用），即用来Mock客户端请求需要的所有数据。
     * @throws Exception
     */
    @Test
    @Ignore
    public void test() throws Exception {
        String param="22";
        MvcResult result =mockMvc.perform(post("/test2/query").
                accept(MediaType.APPLICATION_JSON_UTF8).content(param))//执行请求
                .andExpect(status().isOk())//验证状态码
                .andDo(print())//输出MvcResult到控制台
                .andReturn();
        Assert.assertNotNull(result.getResponse().getContentAsString());//自定义断言
        Assert.assertEquals("success",result.getResponse().getContentAsString());
    }
    //JSON请求/响应验证
    @Test
    public void testJson() throws Exception{
        String requestBody="22";
        mockMvc.perform(post("/test2/query")
                .contentType(MediaType.APPLICATION_JSON_UTF8).content(requestBody)
                .accept(MediaType.APPLICATION_JSON_UTF8)) //执行请求
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) ;//验证响应contentType
                //.andExpect(jsonPath("$.id").value(1)); //使用Json path验证JSON 请参考http://goessner.net/articles/JsonPath/

        String errorBody = "";
        MvcResult result = mockMvc.perform(post("/test2/query")
                .contentType(MediaType.APPLICATION_JSON_UTF8).content(errorBody)
                .accept(MediaType.APPLICATION_JSON_UTF8)) //执行请求
                .andExpect(status().isBadRequest()) //400错误请求
                .andReturn();

        Assert.assertTrue(HttpMessageNotReadableException.class.isAssignableFrom(result.getResolvedException().getClass()));
    }

}
